import { useCallback, useRef, useState } from 'react';

export function useMessageStore() {
  const [message, setMessage] = useState('');
  const [showMessage, setShowMessage] = useState(false);
  const [startHide, setStartHide] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [_confirmText, setConfirmText] = useState('');
  const refData = useRef<{
    confirmOkFn?: () => void;
    confirmCancelFn?: () => void;
  }>({});

  /** 提示消息 */
  const warning = useCallback(function (msg: string) {
    setMessage(msg);
    setShowMessage(true);

    setTimeout(() => {
      setStartHide(true);
    }, 1200);
  }, []);

  /** 提示消息 */
  const success = useCallback(function (msg: string) {
    setMessage(msg);
    setShowMessage(true);

    setTimeout(() => {
      setStartHide(true);
    }, 1200);
  }, []);

  /** 确认框 */
  function confirm(
    message: string,
    okFunc: () => void,
    cancelFunc?: () => void,
  ) {
    setShowConfirm(true);
    setConfirmText(message);
    refData.current.confirmOkFn = okFunc;
    refData.current.confirmCancelFn = cancelFunc;
  }

  function _callConfirmOkFn() {
    if (typeof refData.current.confirmOkFn === 'function') {
      refData.current.confirmOkFn();
    }
    setShowConfirm(false);
  }

  function _callConfirmCancelFn() {
    if (typeof refData.current.confirmCancelFn === 'function') {
      refData.current.confirmCancelFn();
    }
    setShowConfirm(false);
  }

  return {
    message,
    showMessage,
    startHide,
    warning,
    success,
    confirm,
    setShowMessage,
    setStartHide,
    showConfirm,
    _confirmText,
    setConfirmText,
    _callConfirmOkFn,
    _callConfirmCancelFn,
  };
}
